package testApplets;

import peasy.PeasyCam;
import processing.core.PApplet;
import simpleGeom.BasicMesh;
import simpleGeom.Bounds3D;
import simpleGeom.SimpleTriangle;
import testApplets.MeshToSolid2.Cell;

public class Voxelize extends PApplet {
	BasicMesh mesh;
	PeasyCam cam;
public void setup(){
	size(800,800,P3D);
	mesh=new BasicMesh();
	mesh.load("/Users/caad/Desktop/archive/complete/testPiece.obj");
	cam=new PeasyCam(this,800);
	voxelize();
}
float dimCubeX=0.5f;
float dimCubeY=0.5f;
float dimCubeZ=0.5f;
Voxel[][][]grid;
public void voxelize(){
	Bounds3D b3d=mesh.getBounds3D();
	float cX=b3d.getCenterX();
	float cY=b3d.getCenterY();
	float cZ=b3d.getCenterZ();
	int nX=(int)(b3d.getDimX()*0.5f/dimCubeX)+1;
	int nY=(int)(b3d.getDimY()*0.5f/dimCubeY)+1;
	int nZ=(int)(b3d.getDimZ()*0.5f/dimCubeZ)+1;
	float sX=cX-nX*dimCubeX;
	float sY=cY-nY*dimCubeY;
	float sZ=cZ-nZ*dimCubeZ;
	nX=2*nX+1;
	nY=2*nY+1;
	nZ=2*nZ+1;
	grid=new Voxel[nX][nY][nZ];
	for (int x=0;x<nX;x++){
		for (int y=0;y<nY;y++){
			for (int z=0;z<nZ;z++){
				Voxel voxel=new Voxel(x*dimCubeX+sX,y*dimCubeY+sY,z*dimCubeZ+sZ);
				
				grid[x][y][z]=voxel;
				
				for (int i=0;i<mesh.faces.size();i++){
					SimpleTriangle t=(SimpleTriangle)mesh.faces.get(i);
					if (t.getDistance(voxel.x, voxel.y, voxel.z)<(dimCubeX*0.5f)){
						voxel.check=true;
						break;
					}
				}
			}
		}
	}
	
}
public void draw(){
	background(255);
	scale(200);
	stroke(0,0,255);
	mesh.display3D(g);
	noFill();
	stroke(255,0,0);
	int nCubes=0;
	for (int x=0;x<grid.length;x++){
		for (int y=0;y<grid[0].length;y++){
			for (int z=0;z<grid[0][0].length;z++){
				Voxel voxel=grid[x][y][z];
				if (voxel.check){
					nCubes++;
				pushMatrix();
				translate(voxel.x,voxel.y,voxel.z);
				box(dimCubeX,dimCubeY,dimCubeZ);
				popMatrix();
				}
			}
		}
	}
	println(nCubes);
}
class Voxel{
	float x;
	float y;
	float z;
	boolean check;
	Voxel(float x,float y,float z){
		this.x=x;
		this.y=y;
		this.z=z;
	}
}

}
